<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <div class="page-detail">
            <title-name size="24" title="其他类合同"></title-name>
            <a-card v-if="step === 1" v-loading="loading">
                <title-name title="基本信息"></title-name>
                <a-form-model :model="form1" ref="form1Rules" :rules="form1Rules">
                    <a-row>
                        <a-col span="24">
                            <a-form-model-item label="合同名称" prop="contractName">
                                <b-input v-model="form1.contractName" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="所属分公司" prop="branchCompanyId">
                                <SelectSubCompany placeholder="请选择"
                                                  v-model="form1.branchCompanyId"></SelectSubCompany>
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="项目名称" prop="projectId">
                                <SelectProject
                                    placeholder="请选择"
                                    v-model="form1.projectId"
                                    :form="form1"
                                    :is-edit="true"
                                    keyValue="branchCompanyId"
                                ></SelectProject>
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="合同对方" prop="otherParty">
                                <a-input-search placeholder="请选择" v-model="form1.otherParty"
                                                @click="$refs.supplierList.open()"
                                                @search="$refs.supplierList.open()" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="合同额（万元）" prop="amount">
                                <b-input-number :precision="6" v-model="form1.amount" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="24">
                            <a-form-model-item label="合同简要内容" prop="contractContent">
                                <b-textarea v-model="form1.contractContent" />
                            </a-form-model-item>
                        </a-col>

                        <a-col span="8">
                            <a-form-model-item label="主办人">
                                <b-input v-model="form1.creatorName" disabled />
                            </a-form-model-item>
                        </a-col>

                        <a-col span="8">
                            <a-form-model-item label="主办人部门" prop="sponsorId">
                                <a-select v-model="form1.sponsorId">
                                    <a-select-option :key="item.id"
                                                     :value="item.id"
                                                     v-for="item of selectOptionList.posts">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="联系电话">
                                <b-input v-model="form1.creatorPhone" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="创建时间">
                                <b-input :value="form1.createTime|dateFormat" disabled />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </a-card>
            <a-card v-if="step === 2" v-loading="loading">
                <title-name title="用印申请"></title-name>
                <a-form-model :model="form2" ref="form2Rules" :rules="form2Rules">
                    <a-row>
                        <a-col span="24">
                            <a-form-model-item label="合同名称">
                                <b-input disabled v-model="form1.contractName" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="24">
                            <a-form-model-item label="合同对方">
                                <b-input disabled v-model="form1.otherParty" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="申请单位">
                                <b-input disabled v-model="form2.branchCompany" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="合同价（万元）">
                                <b-input disabled v-model="form1.amount" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="合同类型">
                                <b-input disabled value="其他" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="合同份数" prop="contractNum">
                                <b-input-number is-int v-model="form2.contractNum" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="项目经理">
                                <b-input disabled v-model="form2.realityPmName" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="项目经理联系电话">
                                <b-input disabled v-model="form2.realityPmPhone" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="经办人">
                                <b-input disabled v-model="form2.creatorName" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="职务" prop="positionId">
                                <a-select v-model="form2.positionId">
                                    <a-select-option :key="item.id"
                                                     :value="item.id"
                                                     v-for="item of selectOptionList.posts">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="经办人联系电话">
                                <b-input disabled v-model="form2.creatorPhone" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="8">
                            <a-form-model-item label="申请日期">
                                <b-input disabled :value="form2.createTime|dateFormat" />
                            </a-form-model-item>
                        </a-col>
                        <a-col span="24">
                            <a-form-model-item label="特别说明" prop="specialNotes">
                                <b-textarea v-model="form2.specialNotes" />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </a-card>
            <a-card v-if="form1.id">
                <title-name title="相关附件"></title-name>
                <u-table
                    businessCode="LCM08"
                    :listUrl="findFileList"
                    :uploadList="addFile"
                    :deleteUrl="deleteFile"
                    :businessId="form1.id">
                </u-table>
            </a-card>
            <div class="tar page-btn-right-top" v-if="step ===1">
                <a-button v-if="isStep1ShowOptions" type="primary" :loading="loading" @click="submit" class="mr10p">提交
                </a-button>
                <a-button v-if="isStep1ShowOptions" type="primary" :loading="loading" @click="save" class="mr10p">保存
                </a-button>
                <a-button @click="$close">关闭</a-button>
            </div>
            <div class="tar page-btn-right-top" v-if="step ===2">
                <a-button v-if="isStep2ShowOptions" type="primary" :loading="loading" @click="submit" class="mr10p">提交
                </a-button>
                <a-button v-if="form2.sealAuditStatus !== 'SUBMITTED'" type="primary" :loading="loading"
                          @click="save" class="mr10p">保存
                </a-button>
                <a-button @click="$close">关闭</a-button>
            </div>
        </div>
        <supplier-list ref="supplierList" @createList="getSupplier"></supplier-list>
        <a-modal
            :visible="selectJobsVisible"
            class='normal-modal'
            :confirm-loading="loading"
            @ok="baseChangeSubmit"
            @cancel="baseChangeCancel"
        >
            <title-name title="选择岗位"></title-name>
            <a-row>
                <a-col :span="24">
                    <a-form-model-item class="flex" label="组织" prop="orgSelectedName">
                        <TreeSelectOrganization
                            v-model="form.orgSelectedName"
                            :orgSelectedValue.sync="form.orgSelectedName"
                            :orgSelectedLabel.sync="form.orgSelectedLabel"
                            :orgQuery="{pid:orgId,cascade:true}"
                            childrenNode="jobs"
                        ></TreeSelectOrganization>
                    </a-form-model-item>
                </a-col>
                <a-col :span="24">
                    <a-form-model-item class="flex" label="岗位" prop="jobsSelectedName">
                        <Jobs
                            v-model="form.jobsSelectedName"
                            :selectedValue.sync="form.jobsSelectedName"
                            :treeCheckable="true"
                            :addTitel="form.orgSelectedLabel[0]"
                        ></Jobs>
                    </a-form-model-item>
                </a-col>
                <a-col :span="24" v-if="$userType() !== 'CO'">
                    <a-form-model-item label="分管领导" prop="personList" class="flex">
                        <a-tag class="mb10p" :key="item.id" v-for="(item,index) of form.personList">
                            {{ item.name }}
                        </a-tag>
                        <a-tag style="background: #fff; borderStyle: dashed;" @click="selectPersonVisible2 = true">
                            <a-icon type="plus" />
                            选择人员
                        </a-tag>
                    </a-form-model-item>
                </a-col>
            </a-row>
        </a-modal>
        <SelectPerson
            @getSelectPerson="useApplySubmit"
            :list.sync="form.personList"
            title="选择人员"
            mode="single"
            :visible="selectPersonVisible">
        </SelectPerson>
        <SelectPerson
            title="选择人员"
            mode="single"
            :list.sync="form.personList"
            :visible.sync="selectPersonVisible2">
        </SelectPerson>
    </base-breadcrumb>
</template>

<script>

import otherTypeApi from '@/api/legal/branchContract/otherType'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import SupplierList from '@/components/supplierList/supplierList'
import totalPackageContractApi from '@/api/legal/branchContract/totalPackageContract'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import Jobs from '@/components/TreeSelectOrganization/jobs'
import SelectPerson from '@/components/Select/SelectPerson'

export default {
  name:'a'+Date.now(),
  components: {
        SelectSubCompany,
        SelectProject,
        SupplierList,
        TreeSelectOrganization,
        Jobs,
        SelectPerson
    },
    props: {
        isAudit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            loading: false,
            step: 1,
            addFile: otherTypeApi.addFile(),
            deleteFile: otherTypeApi.deleteFile(),
            findFileList: otherTypeApi.findFileList(),
            form1: {
                fileInfoTemp: [],
                contractName: '',
                amount: '',
                contractContent: '',
                projectId: '',
                otherParty: '',
                createName: '',
                createPhone: '',
                createOrg: '',
                createTime: Date.now()
            },
            form1Rules: {
                contractName: { required: true, message: '合同名称不能为空', trigger: 'blur' },
                branchCompanyId: { required: true, message: '所属分公司不能为空', trigger: 'change' },
                projectId: { required: true, message: '项目名称不能为空', trigger: 'change' },
                otherParty: { required: true, message: '合同对方不能为空', trigger: 'blur' },
                amount: { required: true, message: '合同额（万元）不能为空', trigger: 'blur' },
                contractContent: { required: true, message: '合同简要内容不能为空', trigger: 'change' },
                sponsorId: { required: true, message: '主办人部门不能为空', trigger: 'change' }
            },
            form2: {},
            form2Rules: {
                contractNum: { required: true, message: '合同份数不能为空', trigger: 'blur' },
                specialNotes: { required: true, message: '特别说明不能为空', trigger: 'blur' },
                positionId: { required: true, message: '职务不能为空', trigger: 'blur' }
            },
            selectOptionList: {
                posts: []
            },
            selectJobsVisible: false,
            orgId: '',
            form: {
                orgSelectedName: '',
                orgSelectedLabel: '',
                jobsSelectedName: undefined, //岗位
                respEmployeeId: undefined, //人员
                personList:[]
            },

            selectPersonVisible: false,
            selectPersonVisible2: false,
            personList: []
        }
    },
    computed: {
        isStep1ShowOptions() {
            return (!this.form1.reviewAuditStatus) || this.form1.reviewAuditStatus === 'DRAFT' || this.form1.reviewAuditStatus === 'REJECTED'
        },
        isStep2ShowOptions() {
            return (this.form1.reviewAuditStatus !== 'DRAFT') && (!this.form2.sealAuditStatus) || this.form2.sealAuditStatus === 'DRAFT' || this.form2.sealAuditStatus === 'REJECTED'
        }
    },
    created: async function() {
        if (this.$route.query.step) {
            this.step = Number(this.$route.query.step)
        }
        if (this.$route.query.id) {
            this.form1.id = this.$route.query.id
            switch (this.step) {
                case 1:
                    await this.getBaseInfo()
                    break
                case 2:
                    await this.getUsePrintApply()
                    break
            }
        } else {
            let { name, phone } = this.$userInfo().employee
            this.form1.creatorName = name
            this.form1.creatorPhone = phone
        }

        otherTypeApi.queryCurrentUserPost().then(res => {
            if (res.code === this.SUCCESS_CODE) {
                this.selectOptionList.posts.push(res.data)
                this.form2.positionId = this.form1.sponsorId = res.data.id
                this.form2.positionName = this.form1.sponsorName = res.data.name
            }
        })
    },
    methods: {
        getSupplier(row) {
            this.form1.otherParty = row.name
        },
        async getBaseInfo() {
            this.loading = true
            let res = await otherTypeApi.findListByMainId({}, { id: this.form1.id })
            if (res.code === this.SUCCESS_CODE) {
                this.form1 = res.data
            }
            this.loading = false
        },
        async getUsePrintApply() {
            this.loading = true
            let res = await otherTypeApi.findListByMainId({}, { id: this.form1.id })
            if (res.code === this.SUCCESS_CODE) {
                this.form1 = this.$assign(this.form1, res.data)
                let res2 = await otherTypeApi.findSealByBaseId({}, { id: this.form1.id })
                if (res2.code === this.SUCCESS_CODE) {
                    this.form2 = this.$assign(this.form2, res2.data)
                }
            }
            this.loading = false
        },
        async save() {
            return new Promise(((resolve, reject) => {
                switch (this.step) {
                    case 1:
                        this.$refs.form1Rules.validate(async valid => {
                            if (valid) {
                                this.loading = true
                                let res
                                let post = this.selectOptionList.posts.find(w => w.orgId === this.form1.sponsorId)
                                if (post) {
                                    this.form1.sponsorName = post.orgName
                                }
                                this.form1.reviewAuditStatus = 'DRAFT'
                                if (this.form1.id) {
                                    res = await otherTypeApi.editByMain(this.form1)
                                } else {
                                    res = await otherTypeApi.createByMain(this.form1)
                                }
                                if (res.code === 200) {
                                    this.$message.success('保存成功')
                                    this.form1.id = res.data.id
                                    resolve(true)
                                    this.getBaseInfo()
                                }
                                this.loading = false
                            } else {
                                this.$noticeWarning('请填写完整')
                            }
                            resolve(false)
                        })
                        break
                    case 2:
                        this.$refs.form2Rules.validate(async valid => {
                            if (valid) {
                                this.loading = true
                                let post = this.selectOptionList.posts.find(w => w.orgId === this.form2.positionId)
                                if (post) {
                                    this.form2.positionName = post.orgName
                                }
                                this.form2.sealAuditStatus = 'DRAFT'
                                let res = await otherTypeApi.editSeal(this.form2)
                                if (res.code === 200) {
                                    this.$message.success('保存成功')
                                    this.form2.id = res.data.id
                                    resolve(true)
                                    this.getUsePrintApply()
                                }
                                this.loading = false
                            } else {
                                this.$noticeWarning('请填写完整')
                            }
                            resolve(false)
                        })
                        break
                }
            })).then()
        },
        async submit() {
            this.$submitConfirm(async () => {
                if (!await this.save()) {
                    return
                }
                if (this.step === 1) {
                    return this.selectJobsVisible = true
                } else {
                    return this.selectPersonVisible = true
                }
            })
        },
        async useApplySubmit() {
            if (!this.form.personList.length) {
                return this.$noticeWarning('请选择人员')
            } else {
                this.selectPersonVisible = false
            }
            this.loading = true
            let res = await otherTypeApi.generalSubmit({
                baseId: this.form1.id,
                auditStatusEnum: 'SUBMITTED',
                submitCode: 1113,
                assgins: this.form.personList.map(v => v.userId).join(',')

            })
            if (res.code === 200) {
                this.$noticeSuccess('提交成功')
                this.$router.push({ path: '/legal/branch-contract/other-type/index' })
            }
            this.loading = false
        },
        baseChangeCancel() {
            this.form = {
                orgSelectedName: '',
                orgSelectedLabel: '',
                jobsSelectedName: undefined, //岗位
                respEmployeeId: undefined, //人员
                personList:[]
            }
            this.selectJobsVisible = false
            this.selectJobsVisible2 = false
        },
        async baseChangeSubmit() {
            const { jobsSelectedName, personList } = this.form
            if (jobsSelectedName === undefined || jobsSelectedName.length === 0) {
                return this.$noticeWarning('请选择岗位')
            }
            if (this.$userType() !== 'CO') {
                if (personList === undefined || jobsSelectedName.length === 0) {
                    return this.$noticeWarning('请选择提示人员')
                }
            }
            this.loading = true
            let res = await otherTypeApi.generalSubmit({
                auditStatusEnum: 'SUBMITTED',
                baseId: this.form1.id,
                majorRisks: '0',
                submitCode: 1112,
                assgins: jobsSelectedName.join(','),
                managerId: personList[0].userId
            })
            this.loading = false
            if (res.code === 200) {
                this.$noticeSuccess('提交成功')
                setTimeout(() => {
                    this.$close()
                    return Promise.resolve()
                }, this.TIMEOUT_DELAY)
            }
        }
    }
}
</script>
<style lang="less" scoped>
table {
    width: 100%;
    border: 1px solid gainsboro;

    thead {
        background: rgb(244, 244, 244);

        th {
            padding: 10px;
            border: 1px solid gainsboro;
        }
    }

    tbody {
        td {
            padding: 10px;
            border: 1px solid gainsboro;
        }
    }
}

</style>
